<?php

namespace App\Console\Commands;

use App\Episode;
use App\Jobs\FetchTtmjEpisodeDetailJob;
use App\Show;
use GuzzleHttp;
use Illuminate\Console\Command;
use Symfony\Component\DomCrawler\Crawler;

class SpiderTtmj extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'spider:ttmjep';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '爬取下载资源天天美剧网站';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $webURl = 'http://www.ttmeiju.com/index.php/latest/index/date/0.html';
        $client = new GuzzleHttp\Client();
        $headers = config('app.google_bot_headers');
        $headers['referer'] = 'bbs.ttmeiju.com';
        $headers['host'] = 'www.ttmeiju.com';
        $headers['user-agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36';
        $res = $client->request('GET', $webURl, ['headers' => $headers]);
        $html = $res->getBody()->getContents();
        $code = $res->getStatusCode();
        if ($code != 200) {
            \Log::critical('fuck ttmeiju');
            retrun;
        }

        $crawler = new Crawler($html);
        $crawler->filter('tr.Scontent1')->each(function(Crawler $row,$i){
            $raw_name = $row->filterXPath('//td[2]')->text();
            $raw_name = trim($raw_name);
            echo($raw_name . '\n');
            //后去剧集详情页url
            $episode_detail_page_url = $row->filterXPath('//td[2]/a')->attr('href');

            //提取 美剧中文名称
            $zhName='';
            if (preg_match('/^[\x{4e00}-\x{9fa5}]+\W{0,2}[\x{4e00}-\x{9fa5}]*/u',$raw_name, $matches)) {
                $zhName = $matches[0];
                $zhName = trim($zhName);
            }
            echo($zhName . '\n');

            //提取 中文 英文 名称
            $type='';
            $enName='';
            if (preg_match('/.*(?=s\d\d)/i',$raw_name, $matches)) {
                //剧集
                $prefixName = $matches[0];
                $enName = str_ireplace($zhName,'',$prefixName);
                $enName = trim($enName);
                $type = 'ttmjEpisode';
            } elseif (preg_match('/.*(?= \d\d \d\d )/i',$raw_name, $matches)) {
                //脱口秀
                $prefixName = $matches[0];
                $enName = str_ireplace($zhName,'',$prefixName);
                $enName = trim($enName);
                $type = 'ttmjTalkShow';

            }else {
                //电影
                $type = 'ttmjDocumentary';
                $enName = 'ttmjDocumentary';
                $zhName = '颁奖礼|纪录片';
            }

            $episode = Episode::firstOrNew(['raw_name'=>$raw_name]);

            $show_url = $row->filterXPath('//td[1]/a')->attr('href');
            $episode->url_provider = trim($show_url);
            if(str_contains($episode->url_provider,['Moive.'])) {
                $type = 'ttmjMoives';
                $enName = 'ttmjMovie';
                $zhName = '电影';
            }
            $episode->provider = $type;


            $sizeNumber = $row->filterXPath('//td[4]')->text();;
            $formate = $row->filterXPath('//td[5]')->text();
            $episode->size = $sizeNumber.' '.$formate;

            $enName = str_ireplace('(','',$enName);
            $enName = str_ireplace(')','',$enName);
            //$enName = str_ireplace('.',' ',$enName);
            $show = Show::where('name_en','like',$enName.'%')->first();
            //$show = Show::firstOrCreate(['name_en'=>$enName]);
            if($show){
                if($episode->show_id<1) {
                    $episode->show_id = $show->id;
                }
                $show->name_zh = $zhName;
                $show->updated_at = $episode->created_at;
                $show->save();
            } else {
                if($episode->show_id<1) {
                    $episode->show_id = 396;
                }
            }

            $downloadLinks = $row->filterXPath('//td[3]/a');
            if ($downloadLinks->count() > 0) {
                foreach ($downloadLinks as $aLink) {
                    $aLink = new Crawler($aLink);
                    $value = $aLink->attr('href');
                    if (str_contains($value, 'baidu')) {
                        $episode->url_baidupan = $value;
                    } elseif (str_contains($value, 'magnet')) {
                        $episode->url_magnet = $value;
                    } elseif (str_contains($value, 'ed2k')) {
                        $episode->url_ed2k = $value;

                    } elseif (str_contains($value, 'acfun')) {
                        $episode->url_video = $value;
                    } else {
                        $episode->url_other = $value;
                    }


                }
            }
            $episode->name = filterEpisodeRawName($raw_name);
            $episode->save();
            $job = new FetchTtmjEpisodeDetailJob($episode,$episode_detail_page_url);
//            dispatch($job);
        });
//        $this->call('queue:listen');

        unset($html, $client, $crawler, $webURl);
        exec('exit');
    }
}
